import { useCallback, useEffect, useState } from "react";
import * as echarts from 'echarts';

interface IMyChartProps {
    option: echarts.EChartsOption
    title: string
}

const MyChart: React.FC<IMyChartProps> = (props) => {

    const [chart, setchart] = useState<echarts.ECharts>();
    const [isEmptyData, setIsEmptyData] = useState(false);

    // 只在挂载和卸载执行,防止多次初始化
    const chartRef = useCallback((node: HTMLDivElement) => {
        if (node !== null) {
            setchart(echarts.init(node))
        }
    }, []);

    useEffect(() => {
        if (!chart) return;
        // 不同类型的数据图的data位置不同,要加很多条件判断是否有数据
        if (!props.option.series) {
            setIsEmptyData(true);
        }
        else {
            setIsEmptyData(false);
        }
        chart.setOption(props.option);
    }, [props.option])

    return (
        <div style={{minWidth: '600px'}}>
            {
                isEmptyData ? <div style={{
                    position: 'absolute',
                    top: '0',
                    left: '0',
                    width: '100%',
                    marginTop: '100px',
                    textAlign: 'center',
                    fontSize: '40px',
                }}>无{props.title}数据</div> : ''
            }
            <div ref={chartRef} style={{
                width: '100%', 
                height: '300px',
                visibility: isEmptyData ? 'hidden' : 'visible'
            }}></div>
        </div>
    )
}

export default MyChart;

